/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ocnyang.contourviewdemo.slice;

import com.ocnyang.contourview.ContourView;
import com.ocnyang.contourviewdemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.NestedScrollView;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.LinearShader;
import ohos.agp.render.RadialShader;
import ohos.agp.render.Shader;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.IOException;

/**
 * @Description: ContourView效果展示页
 * @Author: yizhihao
 * @CreateDate: 2021/5/27 10:39
 */
public class MainAbilitySlice extends AbilitySlice {
    private DependentLayout dependentLayout;
    private boolean animatorRun = false;
    private int oldScaleX = 0;
    private int oldScaleY = 0;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initCustomContourView();
        initBeachContourView();
        dependentLayout = (DependentLayout) findComponentById(ResourceTable.Id_floatbtn);
        DependentLayout dependTitle = (DependentLayout) findComponentById(ResourceTable.Id_depend_title);
        Text tvSmallTitle = (Text) findComponentById(ResourceTable.Id_tv_small_title);
        Text title = (Text) findComponentById(ResourceTable.Id_title);
        title.setAutoFontSizeRule(14, 24, 1);
        NestedScrollView scrollView = (NestedScrollView) findComponentById(ResourceTable.Id_scroll);
        scrollView.addScrolledListener((component, i0, i1, i2, i3) -> {
            showFloatBtn(pxToVp(i1) < 50);
            if (pxToVp(i1) < 100) {
                if (tvSmallTitle.getVisibility() == Component.VISIBLE) {
                    tvSmallTitle.setVisibility(Component.HIDE);
                    ShapeElement shapeElement = new ShapeElement();
                    shapeElement.setRgbColor(new RgbColor(14, 14, 14, 0));
                    dependTitle.setBackground(shapeElement);
                }
                title.setContentPosition((float) (vpToPx(25) + vpToPx(25) * i1 / vpToPx(100)), title.getContentPositionY());
            } else {
                if (tvSmallTitle.getVisibility() == Component.HIDE) {
                    tvSmallTitle.setVisibility(Component.VISIBLE);
                    ShapeElement shapeElement = new ShapeElement();
                    shapeElement.setRgbColor(new RgbColor(14, 14, 14, 255));
                    dependTitle.setBackground(shapeElement);
                }
            }
        });
        Image imageBack = (Image) findComponentById(ResourceTable.Id_image_back);
        imageBack.setClickedListener(component -> present(new HomeAbilitySlice(), new Intent()));
    }

    /**
     * 显示隐藏悬浮按钮
     *
     * @param isShow 显示隐藏
     */
    private void showFloatBtn(boolean isShow) {
        int scaleX = 0;
        int scaleY = 0;

        AnimatorProperty animatorProperty = dependentLayout.createAnimatorProperty();
        if (isShow) {
            scaleX = 1;
            scaleY = 1;
        }
        if (oldScaleX != scaleX && oldScaleY != scaleY) {
            animatorProperty.cancel();
            animatorRun = false;
            oldScaleX = scaleX;
            oldScaleY = scaleY;
        }
        if (!animatorRun) {
            animatorProperty.scaleX(scaleX).scaleY(scaleY).setDuration(150);
            animatorProperty.start();
            animatorProperty.setStateChangedListener(new Animator.StateChangedListener() {
                @Override
                public void onStart(Animator animator) {
                    animatorRun = true;
                }

                @Override
                public void onStop(Animator animator) {
                }

                @Override
                public void onCancel(Animator animator) {
                }

                @Override
                public void onEnd(Animator animator) {
                    animatorRun = false;
                }

                @Override
                public void onPause(Animator animator) {
                }

                @Override
                public void onResume(Animator animator) {
                }
            });
        }
    }

    /**
     * px转vp
     *
     * @param px px
     * @return vp vp
     */
    private int pxToVp(float px) {
        float scale = DisplayManager.getInstance().getDefaultDisplay(MainAbilitySlice.this).get()
                .getAttributes().scalDensity;
        return (int) (px / scale + 0.5d);
    }

    /**
     * vp转化px
     *
     * @param dp dp
     * @return px px
     */
    private int vpToPx(float dp) {
        float scale = DisplayManager.getInstance().getDefaultDisplay(MainAbilitySlice.this).get()
                .getAttributes().scalDensity;
        return (int) (dp * scale + 0.5d);
    }


    /**
     * 自定义Beach属性
     */
    private void initBeachContourView() {
        try {
            ContourView contourViewBeach = ((ContourView) findComponentById(ResourceTable.Id_contourview_beach));
            Point point = new Point(0, 0);
            Color[] newColors = new Color[]{
                    new Color(getResourceManager().getElement(ResourceTable.Color_startcolor).getColor()),
                    new Color(getResourceManager().getElement(ResourceTable.Color_endcolor).getColor())};
            RadialShader radialGradient = new RadialShader(
                    point,
                    4000,
                    null,
                    newColors,
                    Shader.TileMode.CLAMP_TILEMODE);
            Point[] pointNew = new Point[]{new Point(0, 0), new Point(getWidth(), 400)};
            Color[] linearColors = new Color[]{new Color(Color.argb(30, 255, 255, 255)),
                    new Color(Color.argb(90, 255, 255, 255))};
            LinearShader linearGradient = new LinearShader(pointNew, null,
                    linearColors,
                    Shader.TileMode.REPEAT_TILEMODE);
            contourViewBeach.setShader(radialGradient, linearGradient);
        } catch (NotExistException | IOException | WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, "contourview"), e.getMessage());
        }
    }

    /**
     * 自定义Custom属性
     */
    private void initCustomContourView() {
        ContourView contourViewCustom = (ContourView) findComponentById(ResourceTable.Id_contourview_custom);
        int width = getWidth();
        int hight = 700;
        int[] ints = {width / 2, 50, ((int) (width * 0.75)), hight / 2, ((int) (width * 0.35)), 350};
        int[] intArr = new int[]{width / 5, hight / 3, width / 4 * 3, hight / 2, width / 2,
                ((int) (hight * 0.9)), width / 5, ((int) (hight * 0.8))};
        contourViewCustom.setPoints(ints, intArr);
        try {
            contourViewCustom.setShaderStartColor(new Color(getResourceManager()
                    .getElement(ResourceTable.Color_startcolor).getColor()));
            contourViewCustom.setShaderEndColor(new Color(getResourceManager()
                    .getElement(ResourceTable.Color_endcolor).getColor()));
        } catch (NotExistException | IOException | WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, "contourview"), e.getMessage());
        }
        contourViewCustom.setShaderMode(ContourView.SHADER_MODE_RADIAL);
    }

    /**
     * 获取屏幕宽度
     *
     * @return int 屏幕寬度
     */
    public int getWidth() {
        return DisplayManager.getInstance().getDefaultDisplay(this).get()
                .getAttributes().width;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
